﻿using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using YunLuPos.Com;
using YunLuPos.DB.Utils;
using YunLuPos.Entity;
using YunLuPos.Net.DTO;
using YunLuPos.Net.Http;

namespace YunLuPos.SellView
{
    public partial class SellMemberPay : UIForm
    {
        private Double amount = 0;
        private String outTradeNo = "";
        private String orderCode= "";
        private String bizType = "1";  //1 查询 2 支付
        private String cardNum = "";
        private MebHttp http = new MebHttp();
        public Member member = null;
        public SellMemberPay(String orderCode ,String outTradeNo, Double amount)
        {
            InitializeComponent();
            this.amount = amount;
            this.orderCode = orderCode;
            this.outTradeNo = outTradeNo;
            this.payAmount.Text = amount.ToString("F2");
            this.flowNum.Text = outTradeNo;
            setPaying(false);
        }

        private void SellMemberPay_Load(object sender, EventArgs e)
        {
            this.ActiveControl = this.txtCardNum;
            startRead();
        }


        public void setPaying(Boolean b)
        {
            if (b)
            {
                this.progress.Visible = true;
                if ("1".Equals(bizType))
                {
                    this.message.Text = "查询会员中,请稍后 . . .";
                }
                else
                {
                    this.message.Text = "支付处理中,请稍后 . . .";
                }
                this.txtCardNum.ReadOnly = true;
            }
            else
            {
                this.progress.Visible = false;
                this.message.Text = "";
                this.txtCardNum.ReadOnly = false;
            }
        }


        private void payWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            if ("1".Equals(bizType))
            {
                MebBizBody body = new MebBizBody();
                body.cliqueCode = StaticInfoHoder.commInfo.cliqueCode;
                body.cardNum = cardNum;
                try
                {
                    Member m = http.query(body);
                    e.Result = m;
                }
                catch (BizError bizError)
                {
                    e.Result = bizError.getMsg();
                }catch(NetException ne)
                {
                    e.Result = ne.getMsg();
                }
            }
            else
            {
                if (this.ShowAskDialog("确认使用储值卡消费【" + this.amount.ToString("F2") + "】元？", this.Style))
                {
                    MebBizBody body = new MebBizBody();
                    body.cliqueCode = StaticInfoHoder.commInfo.cliqueCode;
                    body.branchCode = StaticInfoHoder.commInfo.shopCode;
                    body.cahsierCode = StaticInfoHoder.commInfo.cashierCode;
                    body.posCode = StaticInfoHoder.commInfo.posCode;
                    body.cardNum = cardNum;
                    body.amount = this.amount;
                    body.orderCode = this.orderCode;
                    body.flowCode = this.outTradeNo;
                    try
                    {
                        Member m = http.pay(body);
                        e.Result = m;
                    }
                    catch(BizError bizError)
                    {
                        e.Result = bizError.getMsg();
                    }
                    catch (NetException ne)
                    {
                        e.Result = ne.getMsg();
                    }

                }
            }
        }

        private void payWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {

        }

        private void payWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            setPaying(false);
            if(e.Result is String)
            {
                this.message.Text = e.Result.ToString();
                return;
            }

            Member m = (Member)e.Result;
            if ("1".Equals(bizType))
            {
                if(m != null && m.cardNum != null)
                {
                    this.member = m;
                    this.bizType = "2";
                    this.lebName.Text = m.mebName == null ? "不记名" : m.mebName;
                    this.lebPhone.Text = m.phoneNo == null ? "无" : m.phoneNo;
                    this.labCarNum.Text = m.cardNum;
                    this.lebAmount.Text = m.amount.ToString("F2");
                }
                else
                {
                    this.lebName.Text = "未查询到会员";
                    this.lebPhone.Text = "*";
                    this.labCarNum.Text = "*";
                    this.lebAmount.Text = "*";
                }
            }else if ("2".Equals(bizType))
            {
                this.bizType = "1";
                if (m != null && m.cardNum != null)
                {
                    Console.WriteLine("-----------------------");
                    this.DialogResult = DialogResult.OK;
                    //this.result = result;
                    this.Close();
                }
            }
            
        }

        private void txtCardNum_KeyPress(object sender, KeyPressEventArgs e)
        {
            const char Delete = (char)8;
            const char Enter = (char)13;
            if (!(e.KeyChar >= '0' && e.KeyChar <= '9') && e.KeyChar != Delete
                        && e.KeyChar != Enter)
            {
                e.Handled = true;
            }
            else if (e.KeyChar == Enter)
            {
                //回车执行任务
                startBiz();
            }
        }

        void startBiz()
        {
            if ((this.txtCardNum.Text == null || "".Equals(this.txtCardNum.Text)) && "1".Equals(bizType))
            {
                return;
            }
            if ("".Equals(this.cardNum) && "2".Equals(bizType))
            {
                return;
            }
            if (!payWorker.IsBusy)
            {
                this.message.Text = "*";
                cardNum = txtCardNum.Text;
                //this.txtCardNum.Text = "";
                setPaying(true);
                payWorker.RunWorkerAsync();
            }
        }

        private void SellMemberPay_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (payWorker.IsBusy)
            {
                e.Cancel = true;
            }
            cardReadThread.CancelAsync();
        }

        private void cardReadThread_DoWork(object sender, DoWorkEventArgs e)
        {
            Int32 devNum = UMFIC.openUsbDev();
            Console.WriteLine(devNum);
            while (true)
            {

                ulong[] cardNums = new ulong[1];
                Int32 state = UMFIC.findCard(devNum, cardNums);
                if (state == 0)
                {
                    ulong u = cardNums[0];
                    state = UMFIC.cardAuth(devNum, 1);
                    if (state != 0)
                    {
                        /*卡校验错误*/
                        UMFIC.beep(devNum, 10);
                        continue;
                    }
                    String str = UMFIC.cardRead(devNum, 4);
                    if (str != null && !"".Equals(str.Trim()))
                    {
                        str = str.Substring(0, 6);
                        /*读取到卡号*/
                        UMFIC.beep(devNum, 10);
                        UMFIC.closeUsbDev(devNum);
                        e.Result = str;
                        break;
                    }
                    else
                    {
                        /**读取到空值**/
                        UMFIC.beep(devNum, 10);
                        continue;
                    }
                }
                Console.WriteLine("等待寻卡");
                Thread.Sleep(1000);
            }
        }

        public void startRead()
        {
            cardReadThread.RunWorkerAsync();
        }

        private void cardReadThread_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.txtCardNum.Text = e.Result + "";
            startBiz();
        }
    }
}
